package com.yaorange.servlet;

import com.yaorange.dao.CustomerDao;
import com.yaorange.pojo.Customer;
import com.yaorange.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@WebServlet("/register")
public class Register extends HttpServlet {
    Date birthday=null;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //在页面限制他不能为空
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String sex = req.getParameter("gender");
        char gender;
        if (sex.equals("1")){
            gender='男';
        }
        else {
            gender='女';
        }
        String date = req.getParameter("birthday");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            birthday = df.parse(date);
            System.out.println("birthday:"+birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        Date registTime = calendar.getTime();
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        CustomerDao customerDao = sqlSession.getMapper(CustomerDao.class);
        //更具ById查看数据是否存在这个人
        Customer queryCustomerById = customerDao.queryCustomerById(id);
        //调用重写后的equals方法判断两个人是否一样
        Customer customer = new Customer(id, name, birthday, gender, registTime);
        ServletOutputStream outputStream = resp.getOutputStream();

        if (null == queryCustomerById || !queryCustomerById.equals(customer)){
            customerDao.addCustomer(customer);
            sqlSession.commit();
            outputStream.write("<script>".getBytes());
            outputStream.write("alert(\"注册成功，欢迎使用萌萌居家好男人版客户管理系统！\")".getBytes("GBK"));
            outputStream.write("</script>".getBytes());
            outputStream.flush();
            outputStream.close();
        }else {
            outputStream.write("<script>".getBytes());
            outputStream.write("alert(\"注册失败，数据库已存在该用户！\")".getBytes("GBK"));
            outputStream.write("</script>".getBytes());
            outputStream.flush();
            outputStream.close();
        }
        sqlSession.close();
    }
}
